import React, { useMemo, useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import { makeStyles, useTheme, withStyles } from '@material-ui/core/styles';
import AddIcon from '@material-ui/icons/Add';
import DeleteIcon from '@material-ui/icons/Delete';
import {
  useMediaQuery,
  Grid,
  Typography,
  TextField,
  Button, IconButton,
  Divider, Menu, MenuItem,
  Box,
  Tab,
  Tabs
} from '@material-ui/core';
import { Image } from 'components/atoms';
import { SectionHeader } from 'components/molecules';
import { Section } from 'components/organisms';
import { v4 as uuidv4 } from 'uuid'
import { Editor, EditorState } from 'draft-js';
import { DropzoneArea } from 'material-ui-dropzone'
import { blue } from '@material-ui/core/colors';
import { MediaContent } from './components'
import { useSelector, useDispatch } from 'react-redux'
import { setLoading } from 'redux/actions/LoadingActions';
import ReactHtmlParser from 'react-html-parser';
import { useHistory, useParams } from "react-router-dom";
import { setPreURL } from 'redux/actions/AuthActions'
import { callPostApi } from 'utils/networking';


const RedTextTypography = withStyles({
  root: {
    color: "#FF0000",
    marginBottom: '20px'
  }
})(Typography);


function MyEditor(props) {

  const [editorState, setEditorState] = useState(EditorState.createEmpty());
  const [editor, setEditor] = useState(null);

  const onChange = (editorState) => setEditorState(editorState);

  const focusEditor = () => {
    if (editor) {
      editor.focus();
    }
  };

  return (
    <div onClick={focusEditor}>
      <Editor
        ref={setEditor}
        editorState={editorState}
        onChange={onChange}
      />
    </div>
  );
}


function TabPanel(props) {
  const { children, value, index, ...other } = props;

  return (
    <div
      role="tabpanel"
      hidden={value !== index}
      id={`simple-tabpanel-${index}`}
      aria-labelledby={`simple-tab-${index}`}
      {...other}
    >
      {value === index && (
        <Box sx={{ p: 3 }}>
          <Typography>{children}</Typography>
        </Box>
      )}
    </div>
  );
}


TabPanel.propTypes = {
  children: PropTypes.node,
  index: PropTypes.number.isRequired,
  value: PropTypes.number.isRequired,
};


function a11yProps(index) {
  return {
    id: `simple-tab-${index}`,
    'aria-controls': `simple-tabpanel-${index}`,
  };
}

const useStyles = makeStyles(theme => ({
  root: {
    height: '100%',
    width: '100%',
    position: 'relative',
  },
  section: {
    [theme.breakpoints.down('sm')]: {
      paddingTop: 0,
    },
  },
  wrapper: {
    display: 'flex',
    flexDirection: 'column',
    [theme.breakpoints.up('md')]: {
      flexDirection: 'row',
      justifyContent: 'flex-end',
    },
  },
  cover: {
    marginLeft: theme.spacing(-2),
    marginRight: theme.spacing(-2),
    display: 'flex',
    justifyContent: 'center',
    marginBottom: theme.spacing(3),
    [theme.breakpoints.up('sm')]: {
      marginLeft: theme.spacing(-8),
      marginRight: theme.spacing(-8),
    },
    [theme.breakpoints.up('md')]: {
      position: 'absolute',
      top: 0,
      left: 0,
      width: '47vw',
      maxWidth: 740,
      height: '100%',
      marginLeft: 0,
      marginRight: 0,
      marginBottom: 0,
    },
  },
  image: {
    width: '100%',
    height: 300,
    objectFit: 'cover',
    [theme.breakpoints.up('md')]: {
      maxWidth: '100%',
      height: '100%',
    },
  },
  content: {
    flex: '0 0 100%',
    maxWidth: '100%',
    [theme.breakpoints.up('md')]: {
      flex: '0 0 50%',
      maxWidth: '50%',
    },
  },
  addTopMargin: {
    marginTop: '30px'
  },
  medias: {
    marginTop: '30px',
    minHeight: "500px"
  },
  addTopMargin2: {
    marginTop: '50px'
  },
}));


const CreateBlog = () => {
  const classes = useStyles();
  const dispatch = useDispatch();
  let history = useHistory();
  const theme = useTheme();
  const isMd = useMediaQuery(theme.breakpoints.up('md'), {
    defaultMatches: true,
  });

  const profileData = useSelector((state) => state.auth.profileData)
  const category = useSelector((state) => state.community.communityCategoryData)

  const [value, setValue] = useState({ title: '', sub_title: '', description: '' });
  const [currentTab, setCurrentTab] = useState(0);
  const [anchorEl, setAnchorEl] = useState(null);
  const [medias, setMedias] = useState([]);
  const [mediasCount, setMediasCount] = useState(0);
  const [e_value, setEValue] = useState([])
  const [callbackError, setCallbackError] = useState('');

  let uploadingMediaIndex = -1;
  let blogID = 0;

  useEffect(() => {
    if (!profileData || !profileData.id) {
      dispatch(setPreURL(`/community/create`))
      history.push(`/signin`);
    }
  }, [])

  const handleTabChange = (event, newValue) => {
    setCurrentTab(newValue);
  };

  const handleMenu = (event) => {
    setAnchorEl(event.currentTarget);
  };

  const handleMenuItem = (type) => {
    handleClose()

    let uMedias = medias;
    uMedias.push({ id: uuidv4(), type: type, value: null });
    setMedias(uMedias);
    setMediasCount(uMedias.length);
  }

  const deleteMedia = (id) => {
    let uMedias = medias
    for (let i = 0; i < uMedias.length; i++) {
      let element = uMedias[i];
      if (element.id == id) {
        uMedias.splice(i, 1);
        break;
      }
    }
    setMedias(uMedias)
    setMediasCount(uMedias.length)
  }

  const onChangeMedia = (id, value) => {
    let uMedias = [...medias];
    for (let i = 0; i < uMedias.length; i++) {
      let element = uMedias[i];
      if (element.id == id) {
        element.value = value
        break;
      }
    }
    setMedias(uMedias)
    setMediasCount(uMedias.length)
    console.log(medias)
  }

  const onChangeEditor = (id, newValue) => {
    setEValue(newValue)
  }

  const handleClose = () => {
    setAnchorEl(null);
  };

  const onChangeText = (type, newValue) => {
    let uValue = { ...value };
    if (type == "title") {
      uValue.title = newValue;
    } else if (type == "sub_title") {
      uValue.sub_title = newValue;
    } else {
      uValue.description = newValue;
    }
    setValue(uValue);
  }

  const submitBlog = async () => {
    dispatch(setLoading(true))

    if (!value.title) {
      setCallbackError('Please input title');
      return;
    }

    const data = {
      user_id: profileData.id,
      category_id: category.id,
      title: value.title,
      sub_title: value.sub_title ? value.sub_title : '',
      description: value.description ? value.description : ''
    }

    callPostApi('blog/create_blog', data, dispatch, (data) => {
      blogID = data
      uploadMedias()
    })
  }

  const uploadMedias = async () => {
    uploadingMediaIndex++;
    if (uploadingMediaIndex == medias.length) {
      dispatch(setLoading(false))
      history.push(`/community/${category.id}`);
      return;
    }

    const media = medias[uploadingMediaIndex];
    let data = null;

    if (!media.value) {
      return;
    }

    if (media.type == 'text') {
      data = JSON.stringify({
        blog_id: blogID,
        type: media.type,
        pos: uploadingMediaIndex,
        content: media.value
      })
      console.log(data);

    } else if (media.type == 'youtube') {
      data = JSON.stringify({
        blog_id: blogID,
        type: media.type,
        pos: uploadingMediaIndex,
        youtube_link: media.value
      })
      console.log(data);

    } else if (media.type == 'image') {
      data = new FormData()
      data.append('blog_id', blogID);
      data.append('type', 'image')
      data.append('pos', uploadingMediaIndex)
      for (let i = 0; i < media.value.length; i++) {
        data.append(`images[${i}]`, media.value[i]);
      }
      console.log(data);

    } else if (media.type == 'video') {
      data = new FormData()
      data.append('blog_id', blogID);
      data.append('type', 'video')
      data.append('pos', uploadingMediaIndex)
      data.append('video', media.value[0])
      console.log(data);
    }

    console.log('media type', media.type)
    const token = localStorage.getItem("token")
    const requestOptions = {
      method: 'POST',
      headers: (media.type == 'text' || media.type == 'youtube') ? {
        'Content-Type': 'application/json',
        'X-API-KEY': process.env.REACT_APP_API_KEY,
        'Token': token
      } : {
        'X-API-KEY': process.env.REACT_APP_API_KEY,
        'Token': token
      },
      body: data
    };
    fetch(`${process.env.REACT_APP_API_URL}blog/upload_media`, requestOptions)
      .then(response => response.json())
      .then(res => {
        console.log('res', res)
        if (res.status == 1) {
          uploadMedias()

        } else {
          dispatch(setLoading(false))
          setCallbackError(res.error);
        }
      }).catch((error) => {
        dispatch(setLoading(false));
        setCallbackError(error);
        console.log(error);
      });
  }


  return (
    <div className={classes.root}>
      <Section className={classes.section}>
        <div className={classes.wrapper}>
          <div className={classes.cover}>
            <Image
              src="https://assets.maccarianagency.com/the-front/photos/account/cover-4.jpg"
              alt="Contact"
              className={classes.image}
              lazyProps={{ width: '100%' }}
            />
          </div>
          <div className={classes.content}>

            <SectionHeader
              title="Start a Discussion"
              subtitle="Share what's on your mind with the community"
              data-aos="fade-up"
              align="center"
            />
            {(
              <Grid item xs={12}>
                <RedTextTypography
                  align="center"
                  className={classes.errorLabel}
                >
                  {ReactHtmlParser(callbackError)}
                </RedTextTypography>
              </Grid>
            )}
            <Box sx={{ width: '100%' }}>
              <Box sx={{ borderBottom: 1, borderColor: 'divider' }}>
                <Tabs value={currentTab} onChange={handleTabChange} aria-label="basic tabs example">
                  <Tab label="General" {...a11yProps(0)} />
                  <Tab label="Contents" {...a11yProps(1)} />
                </Tabs>
              </Box>
              <TabPanel value={currentTab} index={0}>
                <div className={classes.medias}>
                  <Grid container spacing={isMd ? 4 : 2}>
                    <Grid item xs={12} data-aos="fade-up">
                      <Typography
                        variant="subtitle1"
                        color="textPrimary"
                      >
                        Title *
                      </Typography>
                      <TextField
                        placeholder="Enter title"
                        variant="outlined"
                        size="medium"
                        name="title"
                        fullWidth
                        type="text"
                        onChange={(e) => {
                          onChangeText("title", e.target.value);
                        }}
                        value={value.title}
                      />
                    </Grid>
                    <Grid item xs={12} data-aos="fade-up">
                      <Typography
                        variant="subtitle1"
                        color="textPrimary"
                      >
                        Sub title
                      </Typography>
                      <TextField
                        placeholder="Enter sub title"
                        variant="outlined"
                        size="medium"
                        name="sub_title"
                        fullWidth
                        type="text"
                        onChange={(e) => {
                          onChangeText("sub_title", e.target.value);
                        }}
                        value={value.sub_title}
                      />
                    </Grid>
                    <Grid item xs={12} data-aos="fade-up">
                      <Typography
                        variant="subtitle1"
                        color="textPrimary"
                      >
                        Description
                      </Typography>
                      <TextField
                        placeholder="Enter description about your new post"
                        variant="outlined"
                        name="description"
                        fullWidth
                        multiline
                        minRows={4}
                        value={value.description}
                        onChange={(e) => {
                          onChangeText("description", e.target.value);
                        }}
                      />
                    </Grid>
                  </Grid>
                </div>
              </TabPanel>
              <TabPanel value={currentTab} index={1}>
                <div id='media_container' className={classes.medias}>
                  {/* <MyEditor /> */}

                  <Grid container spacing={isMd ? 4 : 2}>
                    {medias.map((media, index) => (
                      <MediaContent
                        key={media.id}
                        item={media}
                        deleteMedia={deleteMedia}
                        onChangeMedia={onChangeMedia} />
                    ))}
                  </Grid>

                  <Button
                    variant="contained"
                    color="default"
                    className={classes.addTopMargin}
                    startIcon={<AddIcon />}
                    onClick={handleMenu}
                  >
                    Add Media
                  </Button>

                  <Menu
                    id="menu_add_media"
                    anchorEl={anchorEl}
                    anchorOrigin={{
                      vertical: 'top',
                      horizontal: 'right',
                    }}
                    getContentAnchorEl={null}
                    keepMounted
                    open={Boolean(anchorEl)}
                    onClose={handleClose}
                  >
                    <MenuItem onClick={e => {
                      e.stopPropagation()
                      handleMenuItem('text')
                    }}>Text</MenuItem>
                    <MenuItem onClick={e => {
                      e.stopPropagation()
                      handleMenuItem('image')
                    }}>Image</MenuItem>
                    <MenuItem onClick={e => {
                      e.stopPropagation()
                      handleMenuItem('video')
                    }}>Video</MenuItem>
                    <MenuItem onClick={e => {
                      e.stopPropagation()
                      handleMenuItem('youtube')
                    }}>Youtube</MenuItem>
                  </Menu>
                </div>
              </TabPanel>
            </Box>

            <Grid item container justifyContent="center" xs={12} className={classes.addTopMargin2}>
              <Button
                variant="contained"
                type="submit"
                color="primary"
                size="large"
                fullWidth
                onClick={submitBlog}
              >
                Submit
              </Button>
            </Grid>
          </div>
        </div>
      </Section>
      <Divider />
    </div>
  );
};

export default CreateBlog;
